package com.wootion.dizhi.runData;

import com.serotonin.modbus4j.exception.ModbusTransportException;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;

public class ThreadManager {

    private static final Map<String, Thread> threadMap = new HashMap<>();

    /**
     * 线程启动
     * @param taskData 设备从机地址
     * @return
     */
    public static String startThread(Integer taskData) {
        String threadId = UUID.randomUUID().toString();
        Thread thread = new Thread(() -> {
            try {
                runTask(taskData);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        });
        threadMap.put(threadId, thread);
        thread.start();
        return threadId;
    }


    /**
     * 线程任务方法
     * @param taskData 设备从机地址
     */
    private static void runTask(Integer taskData) {
        AtomicBoolean running = new AtomicBoolean(true);

        while (running.get()) {
            //开始读取设备信息
            System.out.println("开始读取设备数据");
            try {
                ModbusUtil.read(taskData);
            } catch (ModbusTransportException e) {
                throw new RuntimeException(e);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            try {
                Thread.sleep(10000); // 每秒打印一次
            } catch (InterruptedException e) {
                e.printStackTrace();
                running.set(false);
                Thread.currentThread().interrupt();
            }
        }
    }

    /**
     * 停止特定线程的方法
     * @param threadId 线程id
     */
    public static void stopThread(String threadId) {
        Thread thread = threadMap.get(threadId);
        if (thread != null) {
            thread.interrupt();
            threadMap.remove(threadId);
        }
    }
}
